<?php
/**
 *  用户登录相关控制器
 */

namespace App\Http\Controllers;

use App\Facades\UserLoginRepo;
use App\Services\AuthToken;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 登录
     * http://www.xxx.com/auth/v1/token?username=hello
     * @param Request $request
     * @return mixed
     */
    public function userLogin(Request $request)
    {
        $requestData = $this->validate($request, [
            'username' => 'required|string',
        ]);

        $userInfo = [
            'user_id' => random_int(1, 100),
            'username' => $requestData['username'],
        ];
        $userInfo['token'] = AuthToken::getJwt(json_encode($userInfo));

        return $this->successData($userInfo);
    }


    /**
     * 获取用户信息
     * http://www.xxx.com/auth/v1/me
     * @param Request $request
     * @return mixed
     */
    public function getUser(Request $request)
    {
        $token = $request->header('Token') ?: $request->input('token') ?: $request->cookie('token');

        $userInfoJson = AuthToken::checkJwt($token);

        $result = [];
        if ($userInfoJson) {
            $result = json_decode($userInfoJson, true);
        }

        return $this->successData($result);
    }

    /**
     * 退出登录接口
     *
     * @param Request $request
     * @return mixed
     */
    public function userLoginOut(Request $request)
    {
        // 退出登录逻辑
        UserLoginRepo::loginOut();

        return $this->success();
    }


}
